import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.select import Select
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys

class Base():
    # 初始化驱动
    def __init__(self,driver):
        self.driver = driver

    # 打开浏览器
    def open_url(self,url):
        self.driver.get(url)

    # 时间的方法
    def time(self,name):
        t = time.strftime('%Y%m%d%H%M%S',time.localtime())
        self.driver.save_screenshot(t + name)

        # 封装定位元素的方法
    def find_element(self,loc):
        # 异常处理
        try:
            WebDriverWait(self.driver,20,0.5).until(lambda driver:driver.find_element(*loc).is_displayed())
            return self.driver.find_element(*loc)
        except Exception as e:
            print(f'元素定位不到{e}')
            # 调用封装时间的方法并截屏
            self.time('error.png')

    # 封装点击的方法
    def click(self,loc):
        self.find_element(loc).click()

    # 封装输入的方法
    def send_keys(self,loc,info):
        self.find_element(loc).send_keys(info)

    # 封装悬浮的方法
    def move_to_element(self,loc):
        a = self.find_element(loc)
        ActionChains(self.driver).move_to_element(a).perform()

    # 封装进入frame框架的方法
    def inframe(self,loc):
        f = self.find_element(loc)
        self.driver.switch_to.frame(f)

    # 封装窗口切换的方法
    def new_window(self):
        self.driver.switch_to.window(self.driver.window_handles[-1])

    # 封装滚动到指定像素的方法
    def scrollTo_x(self,x):
        self.driver.execute_script(f'window.scrollTo(0,{x})')

    # select下拉框 index
    def select_index(self,loc,index):
        s = Select(self.find_element(loc))
        s.select_by_index(index)

    #  select下拉框 value
    def select_value(self,loc,value):
        s = Select(self.find_element(loc))
        s.select_by_value(value)

    #  select下拉框 visible text
    def select_visble_text(self,loc,text):
        s = Select(self.find_element(loc))
        s.select_by_visible_text(text)

    # 封装键盘回车事件的方法
    def Keys_Enter(self,loc):
        self.find_element(loc).send_keys(Keys.ENTER)



